#include <gtest/gtest.h>

// TODO: reimpl with helper::sqlite/shortcut/ *.cpp
#include "memdb/impl/simple/KvTable.h"


using namespace memdb::impl::simple;

static const char * dbPath() {
	return ".";
}
static const char * tableName() {
	return "test_kvtable";
}




/*  

TEST(KvTableTest, testResource){
	KvTable tab(dbPath(), tableName());

	ASSERT_FALSE(tab.isOpened());

  ASSERT_EQ(std::error_code(), tab.open());
	ASSERT_TRUE(tab.isOpened());

  ASSERT_EQ(std::error_code(), tab.close());
	ASSERT_FALSE(tab.isOpened());

  ASSERT_EQ(std::error_code(), tab.open());
	ASSERT_TRUE(tab.isOpened());
  ASSERT_EQ(std::error_code(), tab.close());
	ASSERT_FALSE(tab.isOpened());

  ASSERT_EQ(std::error_code(), tab.destroy());

}

TEST(KvTableTest, testRecords){
	KvTable tab(dbPath(), tableName());

  ASSERT_EQ(std::error_code(), tab.open());
	
	auto && ec = tab.records().insert("1", "1222");
  ASSERT_EQ(std::error_code(), ec);
  ASSERT_EQ(std::error_code(), tab.records().insert("2", "2222"));
  ASSERT_EQ(std::error_code(), tab.records().insert("3", "3222"));
  ASSERT_EQ(std::error_code(), tab.records().insert("4", "4222"));
  ASSERT_EQ(std::error_code(), tab.records().insert("5", "5222"));
  ASSERT_TRUE(tab.records().exists("1"));
  ASSERT_TRUE(tab.records().exists("2"));
  ASSERT_TRUE(tab.records().exists("3"));
  ASSERT_TRUE(tab.records().exists("4"));
  ASSERT_TRUE(tab.records().exists("5"));

  ASSERT_EQ(5ull, tab.records().iterator()->count());

  tab.records().iterator()->foreach([](auto & item){
    std::cout << "all: "  << item->first << "|" << item->second << std::endl;
  });
  tab.records().iterator((size_t)0, (size_t)2)->foreach([](auto & item){
    std::cout << "limit 2 offset 0:"<< item->first << "|" << item->second << std::endl;
  });
  tab.records().iterator("3", (size_t)0, (size_t)2)->foreach([](auto & item){
    std::cout << "key-3 limit 2 offset 0:"<< item->first << "|" << item->second << std::endl;
  });

  ASSERT_EQ(std::error_code(), tab.close());

  ASSERT_EQ(std::error_code(), tab.destroy());
}
*/
TEST(KvTableTest, testExistTable){
	KvTable tab(dbPath(), tableName());

  ASSERT_EQ(std::error_code(), tab.open()); // create or open table already  OK 

  ASSERT_TRUE(tab.TEST_existsTable());

  ASSERT_EQ(0, tab.TEST_dropTable().value()); //drop it
  ASSERT_TRUE(!tab.TEST_existsTable()); // table not exists

  ASSERT_EQ(0, tab.TEST_createTable().value()); // create table ok
  ASSERT_TRUE(tab.TEST_existsTable());

  ASSERT_EQ(std::error_code(), tab.close());
  ASSERT_EQ(std::error_code(), tab.destroy());
}
